using System.Collections.Generic;
using GameFramework.Battle.Core;
using Gameplay.PVE.Entity;
using Gameplay.PVE.Utils;
using UnityEngine;
using Yoozoo.Libs;

namespace Gameplay.PVE
{
    public class ObstacleAvoidComponent : IComponent,ITransmit
    {
        private UnitBase unit;
        private List<Vector3> rayCastStart = new List<Vector3>();
        
        void IClass.OnReset()
        {
            
        }

        void IComponent.OnInitialize(UnitBase unit)
        {
            this.unit = unit;
        }

        void IComponent.OnUpdate()
        {
            
        }

        void IComponent.OnBirth()
        {
            if (unit.Data.unitType == 2)
            {
                rayCastStart.Add(new Vector3(-0.8f * PveUtils.globalRatio * 2.5f,0,0));
                rayCastStart.Add(new Vector3(-0.4f * PveUtils.globalRatio * 2.5f,0,0));
                rayCastStart.Add(new Vector3(0f * PveUtils.globalRatio * 2.5f,0,0));
                rayCastStart.Add(new Vector3(0.4f * PveUtils.globalRatio * 2.5f,0,0));
                rayCastStart.Add(new Vector3(0.8f * PveUtils.globalRatio * 2.5f,0,0));
            }
        }

        void IComponent.OnDead()
        {
            
        }

        void ITransmit.OnTransmit(ETransmitType type,BaseTransmitArg arg)
        {
            if (type == ETransmitType.SearchObstacleFront)
            {
                SearchObstacleFront();
            }
        }


        private void SearchObstacleFront()
        {
            bool hasObstacle = false;
            for (int i = 0; i < rayCastStart.Count; i++)
            {
                var casts = Physics.RaycastAll(GetRayCastStartPositionByForward(rayCastStart[i]) + unit.Data.position, unit.Data.forward, 8 * PveUtils.globalRatio);
                for (int j = 0; j < casts.Length; j++)
                {
                    int id;
                    int.TryParse(casts[j].transform.gameObject.name, out id);
                    if (id == unit.Data.id)
                    {

                    }
                    else
                    {
                        hasObstacle = true;
                        break;
                    }
                }

                if (hasObstacle)
                {
                    break;
                }
            }
            unit.Data.hasObstacleFront = hasObstacle;
        }

        private Vector3 GetRayCastStartPositionByForward(Vector3 offset)
        {
            Vector3 originForward = new Vector3(0,0,1);
            Vector3 currentForward = unit.Data.forward;
            float angle = PveUtils.GetAngle(originForward, currentForward);
            return Quaternion.AngleAxis(angle, Vector3.up) * offset;
        }
    }
}